package de.gwtprime.client.widgets;


import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

import de.gwtprime.client.ClientFactory;
import de.gwtprime.client.PrimeRequestFactory;
import de.gwtprime.client.event.AnswerAddedEvent;
import de.gwtprime.client.event.AnswerOnTypeEvent;
import de.gwtprime.client.user.ACLManager.PrimeUIElement;
import de.gwtprime.client.util.AppUtils;
import de.gwtprime.client.util.HasTextTitleAndProxy;
import de.gwtprime.client.widgets.util.UploadWidget;
import de.gwtprime.shared.requestFactory.AnswerProxy;
import de.gwtprime.shared.requestFactory.QuestionProxy;
import de.gwtprime.shared.requestFactory.request.AnswerRequest;

public class AddAnswerWidget extends Composite implements HasTextTitleAndProxy {

	interface AddAnswerWiddgetUiBinder extends UiBinder<Widget, AddAnswerWidget>{}
	AddAnswerWiddgetUiBinder uiBinder = GWT.create(AddAnswerWiddgetUiBinder.class);

	@UiField TextArea answerText;
	@UiField TooltipButton addAnswerBtn;
	@UiField SimplePanel uploadWidget;
	
	boolean newAnswer = false;
	
	private AnswerProxy answer;
	ClientFactory clientFactory;
	public AddAnswerWidget(final ClientFactory clientFactory){
				
		this(null, clientFactory, null);
		newAnswer=true;
		
	}
	
	public AddAnswerWidget(final QuestionProxy question, final ClientFactory clientFactory, final AnswerProxy answer){
		initWidget(uiBinder.createAndBindUi(this));
		newAnswer= (answer==null || answer.getId() == null);

		this.clientFactory = clientFactory;
		this.answer = answer;
		answerText.getElement().setAttribute("placeholder", "Enter your answere here");
		answerText.addKeyUpHandler(new AnswerChangeHandler());
		
		if(answer!=null){
			answerText.setText(answer.getText());
		}
		
		addAnswerBtn.enableFromUser(clientFactory, PrimeUIElement.AnswerAdd);
		//addAnswerBtn.setEnabled(false);
		addAnswerBtn.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				
				if(!addAnswerBtn.checkEnabledStateAndShowMessage(event)){
					return;
				}
				
				if (!newAnswer) {
					updateExistingAnswer(clientFactory, question);
				} else {
					createNewAnswer(clientFactory, question);
				}
				
				AddAnswerWidget.this.setVisible(false);
				return;
			
			}
		});
		
		uploadWidget.add(new UploadWidget(clientFactory, this));
		
	}
	
	
	public void updateExistingAnswer(ClientFactory clientFactory, QuestionProxy articleSection){
		
		// clear the comments and sections because they cause a lot of lookups
		// TODO better solution?
		
		final PrimeRequestFactory requestFactory = clientFactory.getRequestFactory();
		final AnswerRequest request = requestFactory.answerRequest();

		answer = request.edit(answer);
		answer.setText(answerText.getText());
		
		Request<Long> createReq2 = request.persist().using(answer);
		
		createReq2.fire(new Receiver<Long>() {
			@Override
			public void onSuccess(Long list) {
				AppUtils.log("Answer updated");
			}

			@Override
			public void onFailure(ServerFailure error) {
				AppUtils.log("Answer could not be updated");
			}
		});
	}
	
	public void createNewAnswer(final ClientFactory clientFactory, QuestionProxy question){
		
		final PrimeRequestFactory requestFactory = clientFactory.getRequestFactory();
		final AnswerRequest answerRequest = requestFactory.answerRequest();
		
		
		if(answer==null){
			answer = answerRequest.create(AnswerProxy.class);
		
			answer.setUser(clientFactory.getUser());
		
		}else{
			answer = answerRequest.edit(answer);
		}
		answer.setText(answerText.getText());

		Request<AnswerProxy> createReq2 = answerRequest.addToQuestion(question.getId()).using(answer);
		
		
		createReq2.fire(new Receiver<AnswerProxy>() {
			@Override
			public void onSuccess(AnswerProxy answer) {
				
				clientFactory.getEventBus().fireEvent(new AnswerAddedEvent(answer));
			}

			@Override
			public void onFailure(ServerFailure error) {
				System.out.println("failed"+error); // TODO
			}
		});
		
	}

	@Override
	public String getText() {
		return answerText.getText();
	}

	@Override
	public void setText(String text) {
		answerText.setText(AppUtils.editForClient(text));
		
	}

	@Override
	public String getTitleString() {
		return "";  // Answer has no title
	}

	@Override
	public <T extends EntityProxy> void setProxy(T entity) {
		answer = (AnswerProxy)entity;
		
	}

	@Override
	public <T extends EntityProxy> T getProxy() {
		return (T)answer;
	}

	@Override
	public void setImages(final String images) {
		AnswerRequest request = clientFactory.getRequestFactory().answerRequest();
		
		if(answer == null){
			AnswerProxy answer = request.create(AnswerProxy.class);
			answer.setImages(images);
			request.persist().using(answer).fire();
			this.answer = answer;
			return;
		}
		
		request.findAnswer(answer.getId()).fire(new Receiver<AnswerProxy>() {

			@Override
			public void onSuccess(AnswerProxy response) {
				AnswerRequest request = clientFactory.getRequestFactory().answerRequest();
				response = request.edit(response);
				response.setImages(images);
				request.persist().using(response).fire();
				
				answer = response;
			}
		});
		
	}

	@Override
	public String getImages() {
		if(answer==null)
			return "";
		return answer.getImages();
	}

	@Override
	public void updateTextAndImages(String images, String text) {
		setText(text);
		clientFactory.getEventBus().fireEvent(new AnswerOnTypeEvent(answer == null ? null : answer.getId(), getTitleString(), text, images));	
		
	}
	
	class AnswerChangeHandler implements KeyUpHandler{

		@Override
		public void onKeyUp(KeyUpEvent event) {
			
			clientFactory.getEventBus().fireEvent(new AnswerOnTypeEvent(
							answer == null ? null : answer.getId(), 
							"", 
							answerText.getText(), 
							answer == null ? "" : answer.getImages()));			
		}
	}
		
}

